<template>
  <div class="layout-content">
    <div class="left-content">
      <el-card class="user-card" :body-style="{ padding: '20px' }">
        <div class="title">个人信息</div>
        <div class="info-item">
          <span class="label">姓名</span>
          <span class="info">{{ userInfo.real_name }}</span>
        </div>
        <div class="info-item">
          <span class="label">账号</span>
          <span class="info">{{ userInfo.user_name }}</span>
        </div>
        <div class="info-item">
          <span class="label">手机号</span>
          <span class="info">{{ userInfo.phone_num }}</span>
        </div>
        <!-- <div class="info-item">
                <span class="label">性别</span>
                <span class="info">{{ userInfo.gender }}</span>
            </div> -->
        <div class="info-item">
          <span class="label">角色</span>
          <!-- <span class="info">{{ userInfo.role ? "学生":"老师" }}</span> -->
          <span class="info">{{ userInfo.role }}</span>
        </div>
        <!-- <div class="info-item">
          <span class="label">学院</span>
          <span class="info">{{ userInfo.college }}</span>
        </div> -->
        <!-- <div class="info-item">
                <span class="label">学校</span>
                <span class="info">{{ userInfo.school }}</span>
            </div> -->
        <div class="info-item ">
          <span class="label">所教课程</span>
          <div class="info teach-course">
            <span v-for="(course, index ) in userInfo.courses" :key="index">
              {{ course }}{{ index !== userInfo.courses.length - 1 ? ',' : '' }}
            </span>
          </div>
        </div>
      </el-card>
    </div>
    <div class="right-content">
      <el-card class="right-card" :body-style="{ padding: '20px' }">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="基本信息" name="basic">
            <el-card>
              <el-form ref="basicForm" :model="basicInfo" label-width="100px">
                <el-form-item label="真实姓名">
                  <el-input v-model="basicInfo.real_name" disabled="true" />
                </el-form-item>
                <el-form-item label="用户账号">
                  <el-input v-model="basicInfo.user_name" disabled="true" />
                </el-form-item>
                <!-- <el-form-item label="用户ID">
                        <el-input v-model="basicInfo.userId" />
                        </el-form-item> -->
                <!-- <el-form-item label="性别">
                        <el-select v-model="basicInfo.gender" placeholder="请选择">
                            <el-option label="男" value="男生" />
                            <el-option label="女" value="女生" />
                        </el-select>
                        </el-form-item> -->
                <el-form-item label="手机号">
                  <el-input v-model="basicInfo.phone_num" disabled="true" />
                </el-form-item>
                <!-- <el-form-item label="所属学院">
                  <el-input v-model="basicInfo.college" disabled="true" />
                </el-form-item> -->
                <!-- <el-form-item label="所属学校">
                        <el-input v-model="basicInfo.school" />
                        </el-form-item> -->
                <el-form-item label="身份">
                  <!-- <el-switch v-model="basicInfo.identity" active-text="学生" inactive-text="老师" disabled="true"/> -->
                  <el-input v-model="basicInfo.identity" disabled="true" />
                </el-form-item>
                <el-form-item label="所教课程">
                  <el-checkbox-group v-model="basicInfo.courses" disabled="true">
                    <el-checkbox v-for="course in basicInfo.courses" :key="course" :label="course">{{ course
                      }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

              </el-form>
              <el-button type="primary" @click="saveBasicInfo" disabled="true">保存</el-button>
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="password">
            <el-card>
              <el-form ref="passwordForm" :model="passwordInfo" label-width="100px" :rules="passwordRules">
                <el-form-item label="旧密码" prop="old_password">
                  <el-input type="password" v-model="passwordInfo.old_password" />
                </el-form-item>
                <el-form-item label="新密码" prop="new_password">
                  <el-input type="password" v-model="passwordInfo.new_password" />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input type="password" v-model="passwordInfo.confirmPassword" />
                </el-form-item>
                <!-- <el-form-item label="验证码">
                        <el-input v-model="verificationCode" style="width: 150px" />
                        <span>{{ verificationCode }}</span>
                        </el-form-item> -->
              </el-form>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
            </el-card>
          </el-tab-pane>
          <!-- <el-tab-pane label="修改头像" name="avatar">
                    <el-card>
                    <el-upload
                        action="/uploadAvatar"
                        :show-file-list="false"
                        :on-success="handleAvatarUploadSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <el-button type="primary">点击上传头像</el-button>
                    </el-upload>
                    <img v-if="avatarUrl" :src="avatarUrl" alt="avatar" style="max-width: 200px; max-height: 200px;" />
                    </el-card>
                </el-tab-pane> -->
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getUserInfoId, setChangePassword } from '@/api/person.js'
import { useUserStore } from '@/stores/index'


const userInfo = reactive({
  real_name: '',
  user_name: '',
  phone_num: '',
  gender: '',
  role: false,
  courses: [],
  college: '计算机学院',
  school: '嘉应学院'
});

const activeTab = ref('basic');

const basicInfo = reactive({
  real_name: '',
  user_name: '',
  //   userId: '',
  gender: '',
  phone_num: '',
  college: '',
  school: '',
  courses: [],
  identity: '',
});


const getFormUserInfo = () => {
  basicInfo.real_name = userInfo.real_name
  basicInfo.user_name = userInfo.user_name
  // basicInfo.userId = userInfo.name
  basicInfo.gender = userInfo.gender
  basicInfo.phone_num = userInfo.phone_num
  basicInfo.college = userInfo.college
  basicInfo.school = userInfo.school
  basicInfo.courses = userInfo.courses
  basicInfo.identity = userInfo.role

}

const updateUserInfo = () => {
  userInfo.real_name = basicInfo.real_name
  userInfo.user_name = basicInfo.user_name
  // basicInfo.userId = userInfo.name
  userInfo.gender = basicInfo.gender
  userInfo.phone_num = basicInfo.phone_num
  userInfo.college = basicInfo.college
  userInfo.school = basicInfo.school
  userInfo.courses = basicInfo.courses
  userInfo.role = basicInfo.identity
}

const passwordInfo = ref({
  user_id: 0,
  old_password: '',
  new_password: '',
  confirmPassword: '',
});

const passwordRules = reactive({
  old_password: [
    {
      required: true,
      message: '请输入旧密码',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '密码不能少于6个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === passwordInfo.value.new_password) {
          callback(new Error('新密码不能与旧密码相同'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  new_password: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '密码不能少于6个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value === passwordInfo.value.old_password) {
          callback(new Error('新密码和旧密码不能相同'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请再次输入新密码',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '密码不能少于6个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordInfo.value.new_password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
})

// function checkOldPassword(rule, value, callback) {
//       if (value === passwordInfo.value.newPassword) {
//         callback(new Error('旧密码不能和新密码相同'));
//       } else {
//         callback();
//       }
//     }

//     function checkNewPassword(rule, value, callback) {
//       if (value && value === passwordInfo.value.oldPassword) {
//         callback(new Error('新密码不能和旧密码相同'));
//       } else {
//         callback();
//       }
//     }

//     function validateConfirmPassword(rule, value, callback) {
//       if (value !== passwordInfo.value.newPassword) {
//         callback(new Error('两次输入的新密码不一致'));
//       } else {
//         callback();
//       }
//     }

const verificationCode = ref(generateVerificationCode());
let avatarUrl = ref('');

function handleTabClick(tab) {
  console.log('Tab clicked:', tab);
}

const saveBasicInfo = async () => {
  console.log('Saving basic info:', basicInfo);
  // const res = await 
  // 这里可以添加保存基本信息的逻辑
  updateUserInfo()
}

const changePassword = async () => {
  passwordInfo.value.user_id = uesInfo.userInfo.id

  const res = await setChangePassword(passwordInfo.value)
  console.log(res.data, 'res.data');
  if (res.data.code === 200) {
    ElMessage({
      type: 'success',
      message: `${res.data.msg}`,
    });
  } else {
    ElMessage({
      type: 'error',
      message: `${res.data.msg}`,
    });
  }

}

function generateVerificationCode() {
  // 生成验证码的逻辑，这里简化为随机生成一个 6 位数字
  return Math.floor(Math.random() * 900000 + 100000);
}

function beforeAvatarUpload(file) {
  const isJPG = file.type === 'image/jpeg';
  if (!isJPG) {
    console.error('只能上传 JPG 格式的图片');
  }
  return isJPG;
}

function handleAvatarUploadSuccess(response, file) {
  const { code, data } = response;
  if (code === 200) {
    avatarUrl.value = data.url;
    console.log('Avatar uploaded successfully:', data.url);
  } else {
    console.error('上传头像失败:', response.message);
  }
}


const uesInfo = useUserStore()
//获取个人信息渲染到页面上
const getUserInfo = async () => {
  const res = await getUserInfoId(uesInfo.userInfo.id)
  const resInfo = res.data.data
  userInfo.real_name = resInfo.own.real_name
  userInfo.user_name = resInfo.own.user_name
  userInfo.phone_num = resInfo.own.phone_num
  userInfo.role = resInfo.own.role
  // userInfo.courses.push(resInfo.sub[0].name)
  resInfo.sub.forEach(sub => {
    userInfo.courses.push(sub.name)
  })
  getFormUserInfo()
}



onMounted(() => {
  getUserInfo()
})
</script>

<style scoped>
.layout-content {
  width: 100%;
  height: 75vh;
  display: flex;
  justify-between: space-between;
}

.left-content {
  width: 30%;
  height: 85%;
}

.right-content {
  width: 70%;
  height: 85%;

}

.user-card {
  font-size: 16px;
  /* 调整文字大小为姓名的大小 */
  width: 90%;
  height: 100%;
  margin: 20px auto;
}

.right-card {
  font-size: 16px;
  /* 调整文字大小为姓名的大小 */
  width: 100%;
  height: 100%;
  margin: 20px auto;
}

.title {
  font-size: 16px;
  /* margin-bottom: 20px; */
  text-align: left;
  color: #333;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #ccc
}

.info-item {
  height: 50px;
  line-height: 50px;
  /* margin-bottom: 20px; */
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #ccc
}

.label {
  width: 60%;
  color: #666;
}

.info {
  /* width: 70%; */
  font-size: 16px;
  color: #999;
  /* float: right; */
}

/* .underline {
    height: 1px;
    background-color: #ccc;
    margin-bottom: 20px;
  } */

.teach-course{
  /* 内容过长显示成省略号（内容显示为一行） */
  /*设置不换行*/
  white-space: nowrap;
  /*设置隐藏*/
  overflow: hidden; 
  /*设置隐藏部分为省略号*/
  text-overflow: ellipsis; 
}

</style>